package thread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-09-30
 * Time: 10:57
 */
public class ThreadDemon41 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);//创建10个线程
        Random random = new Random();
        int time = (random.nextInt(4)+1)*1000;//time的范围[0,4]->[1,5]->[1000,5000]
        for(int i = 1 ; i <= 10 ; i++){
            int count = i;
            Thread t = new Thread(() ->{
                try {
                    Thread.sleep(random.nextInt(time));//产生的随机数的范围
                    System.out.println("第" + count + "线程的任务执行完毕");
                    latch.countDown();//告知CountDownLatch有一个任务已经执行完毕了
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
        latch.await();//如果CountDownLatch中的任务还没有执行完毕，那么CountDownLatch就会陷入阻塞等待
        System.out.println("所有任务都已经执行完毕了");
    }
}
